﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media;
using System.IO;

namespace Megaman
{
    

    class Cutscene : IDisposable
    {
        String path;
        struct scene
        {
            public float startTime;
            public float endTime;
            public String line;
            public int imageIndex;
            public Vector2 pos;
        }
        List<scene> scenes;
       
        ContentManager content;
        Song song;
        List<Texture2D> Images;
        SpriteFont font;
        CutsceneHandler handler;
        bool playing = false;

        public Cutscene(IServiceProvider service, String path, CutsceneHandler handler)
        {
            content = new ContentManager(service, "Content");
            this.handler = handler;
            this.path = path;
            try
            {
                song = content.Load<Song>(path + "/Music/song");
            }
            catch (ContentLoadException)
            {
                song = null;
            }
            scenes = new List<scene>();
            Images = new List<Texture2D>();
            int i = 0;
           
            while (i >= 0)
            {
                try
                {
                    Images.Add(content.Load<Texture2D>(path + "/Images/" + i.ToString()));
                    i++;
                }
                catch (ContentLoadException)
                {
                    i = -1;
                }
            }
            string cuesPath = String.Format(path + "/cues.txt");
            cuesPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + cuesPath);
            
            if (!File.Exists(cuesPath))
            {
                throw new Exception("No hay "+cuesPath);
            }

            List<string> lines = new List<string>();
            String[] cue;
            i=0;

            using (StreamReader reader = new StreamReader(cuesPath))
            {
                string line = reader.ReadLine();
                char[] sep = new char[1];
                sep[0] = ';';
                scene scene;
                while (line != null)
                {
                    
                    cue = line.Split(sep);
                    scene = new scene();
                    scene.startTime = float.Parse(cue[0]);
                    scene.endTime = float.Parse(cue[1]);
                    scene.line = cue[2];
                    scene.line  = cue[2].Replace("\\n", "\n");
                    scene.imageIndex = int.Parse(cue[3]);
                    scene.pos = new Vector2(float.Parse(cue[4]),float.Parse(cue[5]));
                    scenes.Add(scene);
                    line = reader.ReadLine();
                }
            }
            font = content.Load<SpriteFont>("Fonts/font");
   

        }

        float time = 0f;
        int index = 0;
        float waitime = 0.5f;
        public void Update(GameTime gameTime)
        {
          KeyboardState state = Keyboard.GetState();
    
          if (!playing)
          {
              MediaPlayer.Stop();
              
              MediaPlayer.Play(song);
              if (MediaPlayer.State == MediaState.Playing )
              playing = true;
          }
          
          time += (float)gameTime.ElapsedGameTime.TotalSeconds;


            if(state.IsKeyDown(Keys.Space))
            {
                if (waitime == 0.5f)
                {
                    index++;
                    time = scenes[index].endTime;
                }

                waitime -= (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (waitime < 0)
                {
                    waitime = 0.5f;
                }
                if (scenes.Count <= index)
                    handler.CutsceneEnd();
            }
          if (scenes[index].endTime < time)
          {

              index++;
              if (scenes.Count <= index)
                  handler.CutsceneEnd();

          }

        }

        public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
        {
            int i = 0;
            spriteBatch.Draw(Images[scenes[index].imageIndex], new Rectangle(0, 0, 1280, 720), Color.White);
            while (scenes[index + i].startTime <= time && scenes[index + i].endTime >= time)
            {
                spriteBatch.DrawString(font, scenes[index+i].line, scenes[index+i].pos, Color.White);
                i++;
                if ((index + i) == scenes.Count)
                    break;
            }
        }





        #region IDisposable Members

        public void Dispose()
        {
            content.Unload();
        }

        #endregion
    }
}
